import i18n from "@/i18n";
import { log } from "console";
import path from "path-browserify";
import { RouteRecordRaw } from "vue-router";

export interface ISearchPoolItem {
  path: string;
  title: string;
}

const filterRoutes = (routes: RouteRecordRaw[]): Array<RouteRecordRaw> => {
  let res: RouteRecordRaw[] = [];
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (hasOneChild(route)) {
      const children = route.children[0];
      res.push({ ...children });
    } else {
      if (!route.meta.hidden) {
        res.push({ ...route });
      }
    }
  }
  return res;
};

/**
 * 是否只有一个子路由
 */
const hasOneChild = (route: RouteRecordRaw) => {
  if (route.children && route.children.length === 1) {
    return true;
  }
  return false;
};
/**
 *
 * @param {*} routes
 * @param {*} basePath
 * @param {*} prefixTitle
 * @returns
 */
export const useGenerateRoutes = (
  routes: RouteRecordRaw[],
  basePath = "/",
  prefixTitle = []
): Array<ISearchPoolItem> => {
  let res: Array<ISearchPoolItem> = [];
  const filterRoutelist = filterRoutes(routes);
  for (const route of filterRoutelist) {
    const data = {
      path: path.resolve(basePath, route.path),
      title: [...prefixTitle, route.meta.title],
    };
    res.push(data);
    if (route.children && route.children.length) {
      const childrenRoutes = useGenerateRoutes(
        route.children,
        data.path,
        data.title
      );
      res = [...res, ...childrenRoutes];
    }
  }
  return res;
};
